<template>
	<scroll-view scroll-y class="scrollSty" @scrolltolower="scrolltolowerFnc">
		<view class="shoppingCart-tmp">
			<!-- 购物车 -->
			<view class="shoppingCart-main">
				<view class="shoppingCart-tagsList">
					<view class="tagsItem" :class="[currentNum == 0 ? 'active' : '']" @click="changeTabs(0)">
						<text>全国送{{cloudNum?`(${cloudNum})`:''}}</text>
						<text class="tagsItem-border" :class="[currentNum == 0 ? 'active' : '']"></text>
					</view>
					<view class="tagsItem" :class="[currentNum == 1 ? 'active' : '']" @click="changeTabs(1)">
						<text>闪电送{{flashNum?`(${flashNum})`:''}}</text>
						<text class="tagsItem-border" :class="[currentNum == 1 ? 'active' : '']"></text>
					</view>
				</view>

				<!-- 订单 -->
				<view v-if="orderList.length > 0">
					<view class="shoppingCart-orderList" v-for="(jitem, index) in orderList" :key="index">
						<view class="shoppingCart-orderList-header">
							<view class="shoppingCart-orderList-ps">
								<u-checkbox-group v-model="selectAllShop[index]" @change="(id) => selectGroupAllShop(id, jitem.goodsList, index)" shape="circle">
									<u-checkbox activeColor="#e43927" :label="jitem.store_id ? jitem.store_name : '全国云仓配送'" :name="index"></u-checkbox>
								</u-checkbox-group>
							</view>
							<view class="shoppingCart-orderList-tag">
								<u-tag :text="currentNum ? '闪电送' : '全国送'" type="error" size="mini"></u-tag>
							</view>
						</view>

						<view class="orderList">
							<u-checkbox-group v-model="checkboxValue[index]" shape="circle" @change="(id) => changeAllShop(id, index)">
								<uni-swipe-action>
									<uni-swipe-action-item v-for="(item, jindex) in jitem.goodsList" :key="item.id">
										<view class="changeShopMain">
											<u-checkbox activeColor="#e43927" label=" " :name="item.id"></u-checkbox>
											<hwxcOrderItem :orderInfo="item" @updataOrder="(option) => getUpdataOrder(option, index)" />
										</view>
										<template v-slot:right>
											<view class="swipe-action-btnList">
												<view class="swipe-action-btn" @click="getCollectOrder(item.id)" style="margin-left: 20rpx; background-color: rgb(248, 148, 52)">
													<view class="btn">
														<uni-icons type="star-filled" size="28" color="#fff" style="margin-bottom: 20rpx"></uni-icons>
														<text>收藏</text>
													</view>
												</view>
												<view class="swipe-action-btn" @click="deleteShop(item.id)" style="background-color: rgb(245, 72, 66)">
													<view class="btn">
														<uni-icons type="trash-filled" size="28" color="#fff" style="margin-bottom: 20rpx"></uni-icons>
														<text>删除</text>
													</view>
												</view>
											</view>
										</template>
									</uni-swipe-action-item>
								</uni-swipe-action>
							</u-checkbox-group>
						</view>
					</view>
				</view>

				<!-- 购物车空 -->
				<view class="cart-none" v-else>
					<u-empty mode="car" icon="http://cdn.uviewui.com/uview/empty/car.png"></u-empty>
					<view class="btn" style="margin: 20rpx 0px" @click="gotoPath(`/pages/shopping/shopping?search_type=${currentNum}`)">前往选购</view>
				</view>

				<!-- 热销产品-->
				<view class="shoppingCart-hotShop">
					<view class="hotShop-title" style="display: flex; align-items: center; justify-content: center">
						<view class="imgSty"></view>
						<image
							src="https://test-zyxx-img.oss-cn-shenzhen.aliyuncs.com/uploads/20241209/129e6e2b9af09cad149ce1fcd976c8f2.png"
							mode="widthFix"
							style="width: 240rpx; margin: 0px 20rpx"
						></image>
						<view class="imgSty"></view>
					</view>
					<view class="hotShop">
						<hwxcShopItem :shopList="shopListData" shopType="0" @refresh="getRefresh" />
					</view>
				</view>
			</view>

			<!-- 结算 -->
			<view class="shoppingCart-shopBtn" v-if="orderList.length > 0">
				<view class="shopBtn-radio">
					<u-checkbox-group v-model="allShopValue" @change="changeSelectAllShop" shape="circle">
						<u-checkbox activeColor="#e43927" label="全选" name="all"></u-checkbox>
					</u-checkbox-group>
				</view>
				<view class="shopInfoData">
					<text>已选{{ getShopNum() }}件，</text>
					<text>合计</text>
					<text class="shop-pir">
						<text style="font-size: 24rpx">￥</text>
						{{ totalAmount() }}
					</text>
				</view>
				<view class="shopBtn" @click="settleAccount">
					<u-button type="primary" shape="circle" text="去结算" style="width: 220rpx" color="#e43927"></u-button>
				</view>
			</view>
			
			<hwxcTabbar/>
		</view>
	</scroll-view>
</template>

<script>
import hwxcOrderItem from '../../components/hwxcOrderItem/hwxcOrderItem.vue';
import hwxcShopItem from '../../components/hwxcShopItem/hwxcShopItem.vue';
import { flashgetCart, flashdelCart } from '../../api/flash/index.js';
import { homeGoodsList, cloudGetCart, cloudDelCart, userCollect, cloudCartNum } from '../../api/home/index.js';
import { imageUrl } from '../../utils/tools';
import hwxcTabbar from '../../components/hwxcTabbar.vue';
export default {
	data() {
		return {
			currentNum: 0,
			// 购物车数据
			orderList: [],
			// 商品参数
			shopQuery: {
				page: 1,
				limit: 10,
				category_id: '',
				type: '0',
				store_id: '0'
			},
			// 商品数据
			shopListData: [],

			selectAllShop: {},
			checkboxValue: {},
			allShopValue: [],
			orderShopChange: {},
			ratio: 0,
			tokenValue: '',
			cloudNum:0,
			flashNum:0
		};
	},

	components: {
		hwxcOrderItem,
		hwxcShopItem,
		hwxcTabbar
	},

	onShareAppMessage() {
		return {
			title: '购物车',
			path: 'pages/shoppingCart/shoppingCart'
		};
	},

	onShareTimeline() {
		return {
			title: '购物车',
			query: 'pages/shoppingCart/shoppingCart'
		};
	},

	async onLoad() {
		this.ratio = this.$store.state.commInitInfo.yyd_ratio;
		await this.getHomeGoodsList();
	},

	async onShow() {
		this.orderShopChange = {};
		this.selectAllShop = {};
		this.checkboxValue = {};
		this.allShopValue = [];
		this.current = 0;
		this.list = [];
		this.tokenValue = (await uni.getStorageSync('token')) || '';

		if (this.tokenValue) {
			await this.getcloudCartNum();
			await this.getCloudGetCart();
		} else {
			uni.showModal({
				title: '温馨提示',
				content: '登录后才可以操作',
				confirmText: '去登录',
				cancelText: '我知道了',
				confirmColor: '#e43927',
				success: async (res) => {
					if (res.confirm) {
						uni.reLaunch({
							url: '/pages/loginMain/loginMain'
						});
					}
				}
			});
		}
	},

	methods: {
		// 获取商品数据
		async getHomeGoodsList() {
			try {
				const resData = await homeGoodsList(this.shopQuery);
				let list = resData.data.data || [];
				const shopListData = [...(this.shopListData || []), ...list];
				shopListData.forEach((item) => {
					item.image = imageUrl(item.fileUrl);
				});
				this.shopListData = shopListData;
			} catch (e) {
				throw Error(e);
			}
		},

		async getcloudCartNum(type) {
			try {
				const cloudResData = await cloudCartNum({
					type: 0
				});
				this.cloudNum = cloudResData.data;
				const flashResData = await cloudCartNum({
					type: 1
				});
				this.flashNum = cloudResData.data;
			} catch (e) {
				throw Error(e);
			}
		},

		// 触底加载
		scrolltolowerFnc() {
			this.shopQuery.page++;
			this.getHomeGoodsList();
		},

		// 切换全国送or闪电送
		async changeTabs(index) {
			this.orderList = [];
			this.currentNum = index;
			this.orderShopChange = {};
			this.selectAllShop = {};
			this.checkboxValue = {};
			this.allShopValue = [];
			await this.getCloudGetCart();
		},

		// 购物车数据
		async getCloudGetCart() {
			try {
				const resData = await cloudGetCart({
					type: this.currentNum
				});
				const shopCardList = resData.data;
				const groupedData = {};
				shopCardList.forEach((item) => {
					const storeId = item.store.id;
					const storeName = item.store.name;
					if (!groupedData[storeId]) {
						groupedData[storeId] = {
							store_id: storeId,
							store_name: storeName,
							goodsList: []
						};
					}
					groupedData[storeId].goodsList.push(item);
				});
				const finalResult = Object.values(groupedData);
				this.orderList = finalResult;
			} catch (e) {
				throw Error(e);
			}
		},

		// 刷新购物车数据
		async getRefresh() {
			this.list = [];
			await this.getcloudCartNum();
			await this.getCloudGetCart();
		},

		// 更新购物车商品数量
		getUpdataOrder(option, index) {
			const { id, num } = option;
			this.orderList[index].goodsList.forEach((item) => {
				if (item.id == id) {
					item.num = num;
				}
			});
			const keys = Object.keys(this.orderShopChange);
			if (keys.length > 0) {
				const list = this.orderShopChange[index];
				list.forEach((item) => {
					if (item.id == id) {
						item.num = num;
					}
				});

				console.log(this.orderShopChange);
			}

			this.totalAmount();
		},

		// 收藏商品
		async getCollectOrder(id) {
			try {
				const resData = await userCollect({
					id
				});
				uni.showToast({
					title: resData.msg,
					icon: 'none'
				});
			} catch (e) {
				throw Error(e);
			}
		},

		// 删除商品
		async deleteShop(id) {
			await this.getDeleteOrder(id);
		},

		//  删除商品
		async getDeleteOrder(id) {
			try {
				const resData = await cloudDelCart({
					ids: [id],
					type: this.currentNum
				});
				uni.showToast({
					title: '删除成功',
					icon: 'none'
				});
				this.list = [];
				await this.getcloudCartNum();
				setTimeout(() => {
					this.getCloudGetCart();
				}, 500);
			} catch (e) {
				throw Error(e);
			}
		},

		// 跳转
		gotoPath(path) {
			uni.navigateTo({
				url: path
			});
		},

		// 结算
		settleAccount() {
			// 清除购物车缓存数据
			this.$store.commit('clearCartShopList');
			const keys = Object.keys(this.orderShopChange);
			const hasValues = keys.some((key) => this.orderShopChange[key].length > 0);
			if (keys.length > 0 && hasValues) {
				const shopList = Object.values(this.orderShopChange).flat();
				let orderListArr = [];
				shopList.forEach((item) => {
					if (this.currentNum == 0) {
						orderListArr.push({
							...item.goods,
							card_id: item.id,
							num: item.num
						});
					} else {
						orderListArr.push({
							...item.goods,
							card_id: item.id,
							num: item.num
						});
					}
				});

				// 勾选的商品
				this.$store.dispatch('getCartShopListAsync', orderListArr);

				uni.navigateTo({
					url: `/pages/submitOrder/submitOrder?type=${this.currentNum}`
				});
			} else {
				return uni.showToast({
					title: '请勾选商品',
					icon: 'error'
				});
			}
		},

		// 全选
		changeSelectAllShop(idList) {
			if (idList.length > 0) {
				this.orderList.forEach((item, index) => {
					this.selectAllShop[index] = [index];
					this.checkboxValue[index] = item.goodsList.map((jitem) => jitem.id);
					this.orderShopChange[index] = item.goodsList;
				});
			} else {
				this.selectAllShop = {};
				this.checkboxValue = {};
				this.orderShopChange = {};
			}
			this.totalAmount();
		},

		// 分组全选
		selectGroupAllShop(idlist, info, index) {
			this.selectAllShop[index] = idlist;
			if (idlist.length > 0) {
				this.checkboxValue[index] = info.map((item) => item.id);
				this.orderShopChange[index] = info;
			} else {
				this.checkboxValue[index] = [];
				this.orderShopChange[index] = [];
			}
			this.getIsAll();
		},

		// 选择商品
		changeAllShop(idList, index) {
			if (idList.length == this.orderList[index].goodsList.length) {
				this.selectAllShop[index] = [index];
				this.orderShopChange[index] = this.orderList[index].goodsList;
			} else {
				this.selectAllShop[index] = [];
				const shopList = [];
				this.orderList[index].goodsList.forEach((item) => {
					if (idList.indexOf(item.id) > -1) {
						shopList.push(item);
					}
				});
				this.orderShopChange[index] = shopList;
			}
			this.getIsAll();
		},

		// 判断是否全选
		getIsAll() {
			const keys = Object.keys(this.selectAllShop);
			const hasValues = keys.every((key) => this.selectAllShop[key].length > 0);
			if (keys.length == this.orderList.length && hasValues) {
				this.allShopValue = ['all'];
			} else {
				this.allShopValue = [];
			}
			this.totalAmount();
		},

		// 合计金额
		totalAmount() {
			let amountAll = 0;
			const keys = Object.keys(this.orderShopChange);
			if (keys.length > 0) {
				for (let key in this.orderShopChange) {
					if (this.orderShopChange[key].length > 0) {
						this.orderShopChange[key].forEach((item) => {
							if (item.goods.type == 0) {
								if (!item.goods.store_id) {
									const pic = item.goods.price != '0.00' ? item.goods.price : item.goods.saleprice;
									amountAll = amountAll + item.num * (Number(pic) * (this.ratio / 100) + Number(pic)).toFixed(2);
								} else {
									amountAll = amountAll + item.num * (item.goods.price != '0.00' ? item.goods.price : item.goods.saleprice);
								}
							} else {
								amountAll = amountAll + item.num * (item.goods.price != '0.00' ? item.goods.price : item.goods.saleprice);
							}
						});
					}
				}
				return amountAll.toFixed(2);
			} else {
				return '0.00';
			}
		},

		// 商品数量
		getShopNum() {
			const shopList = Object.values(this.orderShopChange).flat();
			return shopList.length;
		}
	}
};
</script>

<style>
page {
	display: flex;
	flex-direction: column;
	height: 100%;
}
</style>

<style scoped lang="scss">
.scrollSty {
	flex: 1;
	overflow: scroll;
}
.shoppingCart-tmp {
	.shoppingCart-main {
		box-sizing: border-box;
		padding: 20rpx;
		padding-top: 0px;
		.shoppingCart-tagsList {
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			.tagsItem {
				width: 100px;
				font-size: 28rpx;
				color: #606266;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				.tagsItem-border {
					display: inline-block;
					height: 3px;
					width: 26px;
					background-color: transparent;
					margin-top: 3px;
					border-radius: 2px;
				}

				.active {
					background-color: #f56c6c;
				}
			}

			.active {
				color: #303133;
				font-weight: bold;
				transform: scale(1.05);
			}
		}

		.shoppingCart-orderList {
			background-color: #fff;
			box-sizing: border-box;
			padding: 20rpx;
			border-radius: 24rpx;
			padding-top: 10rpx;
			margin-bottom: 30rpx;
			.shoppingCart-orderList-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 80rpx;
				border-bottom: 1px #f3f3f3 solid;
			}
		}

		.cart-none {
			height: 500rpx;
			background-color: #fff;
			border-radius: 24rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			.cartImage {
				width: 240rpx;
				height: 240rpx;
			}

			.title {
				display: block;
				margin: 20rpx 0px;
				font-size: 26rpx;
				color: #666;
			}

			.btn {
				height: 70rpx;
				line-height: 70rpx;
				text-align: center;
				background-color: red;
				color: #fff;
				border-radius: 70rpx;
				font-size: 28rpx;
				width: 240rpx;
			}
		}

		.shoppingCart-hotShop {
			padding-bottom: 120rpx;
			.hotShop-title {
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				font-size: 28rpx;
				color: #999;
			}

			.imgSty {
				width: 100rpx;
				height: 1px;
				background-color: #d9d9d9;
				display: inline-block;
			}
		}
	}

	.shoppingCart-shopBtn {
		display: flex;
		align-items: center;
		justify-content: flex-start;
		height: 120rpx;
		background-color: #fff;
		border-top-right-radius: 24rpx;
		border-top-left-radius: 24rpx;
		box-sizing: border-box;
		padding: 0px 20rpx;
		position: fixed;
		left: 0px;
		bottom: 85px;
		width: 100%;
		z-index: 999;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		.shopBtn-radio {
			width: 120rpx;
			margin-top: 3px;
		}

		.shopInfoData {
			flex: 1;
			font-size: 24rpx;
			.shop-pir {
				font-size: 34rpx;
				font-weight: bold;
				color: #e43927;
			}
		}

		.shopBtn {
			width: 220rpx;
			text-align: center;
		}
	}
}

.changeShopMain {
	display: flex;
	align-items: center;
}

.swipe-action-btnList {
	width: 100%;
	height: 100%;
	display: flex;
	.swipe-action-btn {
		width: 120rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #fff;
		.btn {
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;
			font-size: 26rpx;
		}
	}
}

::v-deep .uni-swipe {
	border-radius: 20rpx;
	overflow: hidden;
}
</style>
